﻿Imports System.IO
Imports TyranntEngine

Public NotInheritable Class SplashScreen

    Private _clientMajor As Integer = 0
    Private _clientMinor As Integer = 1
    Private _clientPatch As Integer = 7

    Private WithEvents _client As New TyranntWelcomeService.WelcomeClient
    Private _character As New TyranntOnlineCharacterService.TyranntCharacterServiceClient

    Private Sub SplashScreen_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'Application title
        If My.Application.Info.Title <> "" Then
            ApplicationTitle.Text = My.Application.Info.Title
        Else
            'If the application title is missing, use the application name, without the extension
            ApplicationTitle.Text = System.IO.Path.GetFileNameWithoutExtension(My.Application.Info.AssemblyName)
        End If

        Version.Text = _clientMajor.ToString + "." + _clientMinor.ToString + "." + _clientPatch.ToString

        'Copyright info
        Copyright.Text = My.Application.Info.Copyright

        ' Display splash screen
        Me.Show()
        Me.Refresh()
        ' Now call the welcome service to make sure we are all up-to-date
        Welcome()

    End Sub

    Private Sub Welcome()
        'MessageBox.Show(_character.GetCharacterGuild(1))
        Try
            _client.HelloAsync(_clientMajor, _clientMinor, _clientPatch)
        Catch ex As Exception
            Dim err As New ErrorDlg
            err.ShowDialog(ex.Message, "Fatal Error trying to handshake with server")
            End
        End Try

    End Sub

    Private Sub MainRoutine()
        Dim reg As New RegisterControl
        Dim log As New LogonControl

        Do
            Select Case log.ShowDialog
                Case DialogResult.OK
                    Select Case log.UserGroup
                        Case 1
                            Me.Hide()
                            Dim admin As New adminForm
                            admin.TokenString = log.TokenString
                            admin.AdminUsername = log.usernameTextbox.Text
                            admin.ShowDialog()
                        Case Else
                            Me.Hide()
                            Dim user As New mainForm
                            user.SetDetails(log.TokenString, log.UserAlias, log.UserGroup)
                            user.ShowDialog()
                    End Select
                Case DialogResult.Ignore
                    reg.usernameTextBox.Text = log.usernameTextbox.Text
                    If reg.ShowDialog() = Windows.Forms.DialogResult.OK Then
                        Select Case reg.UserGroup
                            Case 1
                                Me.Hide()
                                Dim admin As New adminForm
                                admin.TokenString = reg.TokenString
                                admin.AdminUsername = log.usernameTextbox.Text
                                admin.ShowDialog()
                            Case Else
                                Me.Hide()
                                Dim user As New mainForm
                                user.SetDetails(reg.TokenString, reg.UserAlias, reg.UserGroup)
                                user.ShowDialog()
                        End Select
                    End If
                Case DialogResult.Cancel
                    End
            End Select
            ' Display splash screen
            Me.Show()
            Me.Refresh()
        Loop
    End Sub

    Private Sub _client_HelloCompleted(ByVal sender As Object, ByVal e As TyranntWelcomeService.HelloCompletedEventArgs) Handles _client.HelloCompleted
        If e.Result.Message.Contains("[#]") Then
            MessageBox.Show(e.Result.Message, "Fatal Handshaking Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End
        End If
        If e.Result.UpdateRequired = True Then
            GetChangedFiles(e.Result.Message, e.Result.ServerVersion)
        Else
            MainRoutine()
        End If
    End Sub

    Private Function GetChangedFiles(ByVal filesXMLString As String, ByVal version As String) As String
        ' convert the list of files to a proper XElement
        Dim sr As New StringReader(filesXMLString)
        Dim serverFiles As XElement = XElement.Load(sr)

        ' now check the local files
        Dim coreDir As New DirectoryInfo(".")
        Dim coreFiles() As FileInfo = coreDir.GetFiles()
        Dim mediaDir As New DirectoryInfo(".\media")
        Dim mediaFiles() As FileInfo = mediaDir.GetFiles
        Dim filesXML = <files>
                           <%= From aFile In coreFiles _
                               Select <file name=<%= ".\" + aFile.Name %> size=<%= aFile.Length %> hash=<%= GetFileHash(aFile.FullName) %>/> %>

                           <%= From aFile In mediaFiles _
                               Select <file name=<%= ".\media\" + aFile.Name %> size=<%= aFile.Length %> hash=<%= GetFileHash(aFile.FullName) %>/> %>
                       </files>

        ' process core files and see which files need downloading
        ' and which files need removing
        Dim files As New GameFileCollection
        Dim updaterFiles As New GameFileCollection
        Dim updaterDownload As Boolean = False

        For Each serverEle As XElement In serverFiles...<file>
            Dim found As Boolean = False
            Dim filename As String = serverEle.<name>.Value
            Dim size As Long = Long.Parse(serverEle.<size>.Value)
            Dim hash As String = serverEle.<hash>.Value
            For Each localEle As XElement In filesXML...<file>
                If localEle.@name = filename Then
                    found = True
                    If localEle.@hash <> hash Then
                        If filename.ToLower.Contains("tyranntupdater") = True Then
                            updaterDownload = True
                            Dim file As New GameFile
                            file.Filename = filename
                            file.Action = "download"
                            file.Size = size
                            updaterFiles.Add(file)
                            Exit For
                        Else
                            Dim file As New GameFile
                            file.Filename = filename
                            file.Action = "download"
                            file.Size = size
                            files.Add(file)
                            Exit For
                        End If
                    End If
                End If
                If found = True Then
                    Exit For
                End If
            Next
            If found = False Then
                If filename.ToLower.Contains("tyranntupdater") = True Then
                    updaterDownload = True
                    Dim file As New GameFile
                    file.Filename = filename
                    file.Action = "download"
                    file.Size = size
                    updaterFiles.Add(file)
                Else
                    Dim file As New GameFile
                    file.Filename = filename
                    file.Action = "download"
                    file.Size = size
                    files.Add(file)
                End If
            End If
        Next

        ' we now have our two lists, so lets create a new work xml
        ' document for the updater program
        Dim workXML = <files>
                          <%= From aFile In files _
                              Select <file name=<%= CType(aFile, GameFile).Filename %> size=<%= CType(aFile, GameFile).Size.ToString %> action=<%= CType(aFile, GameFile).Action %>/> %>
                      </files>
        If MessageBox.Show("Client is out of date, do you wish to update client?" + vbCrLf + vbCrLf + "Click Ok to update or Cancel to exit client", "Update client to " + version, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK Then
            ' Write away work list
            workXML.Save(".\updater\workfile.xml")

            ' Now check to see if the downloader update is required.
            If updaterDownload = True Then
                ' we need to do this first so...
                Dim updater As New updaterForm(updaterFiles)
                updater.ShowDialog()
            End If
            Shell(".\TyranntUpdater.exe", AppWinStyle.NormalFocus, False)
            ' and exit
            End
        End If

        ' User does not wish to update so exit
        End

    End Function
End Class
